#!/usr/bin/env python 
#encoding=utf-8

#模拟www.med66.com网站的登陆过程

import urllib
import urllib2
import cookielib
import os
import json
import re
import account

from util import *

def get_randcode_jpeg():
    randcode_url = 'http://portal.cdeledu.com/auth/randcode.php?id=login'
    respond = urllib2.urlopen(randcode_url)
    return respond.read()
    pass

def show_randcode_jpeg():
    jpeg_context = get_randcode_jpeg()
    jpeg_file = 'randcode.jpeg'
    write_file(jpeg_context, jpeg_file)
    os.system('eog "%s"' % jpeg_file)
    os.remove(jpeg_file)

def get_randcode():
    #TODO
    # 获取随机验证码
    # http://portal.cdeledu.com/auth/randcode.php?id=login
    # 将验证码展现出来，让用户输入
    show_randcode_jpeg()
    randcode = raw_input('请输入验证码：')
    return randcode
    pass

def parser_json(json_context):
    #给json的key加双引号，不然python json解释会报错
    json_context = re.sub(r'(\w+):', r'"\1":', json_context)
    #将单引号转换成双引号
    json_context = re.sub(r"\'", r'"', json_context)

    json_data = json.loads(json_context)
    return json_data

#合成网址，获取json数据并提取sid码
def get_json(username, password, randcode):
    url_template = 'http://portal.cdeledu.com/auth/index.php?cmd=ucAuth&type=JSON&randid=login&username=%s&passwd=%s&domain=@med66.com&randcode=%s&jsonpCallback=?'
    #合成完整的url
    url_full = url_template % (username, password, randcode)
    respond = urllib2.urlopen(url_full)
    context = respond.read()[2:-1]  #去除开头的?(与后面的)

    json_data = parser_json(context)
    return json_data

#提交submit_form表单到 http://member.med66.com/member/loginDispose.shtm
def submit_form(code, sid):
    url = 'http://member.med66.com/member/loginDispose.shtm'
    url_data = urllib.urlencode({'code':code, 'sid':sid})
    #print(url_data)
    return get_webpage(url, url_data)

#登陆网站，并返回登陆后的页面
def login():
    install_opener()    
    #获取验证码图片，展示并让用户输入验证码
    randcode = get_randcode()   
    if randcode != None:
        #获取json数据，提取code, sid
        json_data = get_json(account.username, account.password, randcode)
        if json_data != None:
            code = json_data['code']
            if code == '0':
                #用code, sid提交submit_form表单，返回登陆后的页面
                submit_form(code, json_data['sid'])
                print('登陆成功')
                return True
            elif code == '-4':
                print('帐户或密码错误')
            elif code == '-6':
                print('验证码错误')
            else:
                print("code:" + code + "msg:" + json_data['msg'])
        else:
            print('获取json失败')
    else:
        print('获取验证码失败')
    return False

def test_randcode():
    show_randcode_jpeg()
    pass

def test_login():
    page = login()
    if page != None:
        write_file(page, 'login.html')

if __name__ == '__main__':
    test_login()
